//
//  DBManager.m
//  kyoku
//
//  Created by Xuan Mai on 1/14/14.
//  Copyright (c) 2014 Xuan Mai. All rights reserved.
//

#import "DBManager.h"
#import "AppDelegate.h"
#import "Account.h"
#import "Global.h"
#import "AccountEntity.h"

#define EntityAccount @"Account"
@implementation DBManager


+ (NSArray *)getRecordWithEntiy:(NSString *)entityName{
    AppDelegate *appDelegate = initDelegate;
    // initializing NSFetchRequest
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    
    //Setting Entity to be Queried
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName
                                              inManagedObjectContext:appDelegate.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError* error;
    
    // Query on managedObjectContext With Generated fetchRequest
    NSArray *fetchedRecords = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    
    // Returning Fetched Records
    return fetchedRecords;

}

+ (NSArray *)getArrayAccounts{
    NSArray * arrAccount = [self getRecordWithEntiy:EntityAccount];
    return arrAccount;
}

+ (void)saveDatabase{
    AppDelegate *appDelegate = initDelegate;
    NSError *error;
    if (![appDelegate.managedObjectContext save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }

}

+ (void)InsertAccount:(AccountEntity *)acc{
    AppDelegate *appDelegate = initDelegate;
    Account * newEntry = [NSEntityDescription insertNewObjectForEntityForName:EntityAccount
                                                             inManagedObjectContext:appDelegate.managedObjectContext];
    newEntry.account = acc.account;
    newEntry.result = acc.result;
    newEntry.attempted = acc.attempted;
   
    [self saveDatabase];

}


#pragma mark - PROGRAM 



@end
